<?php
/**
 * 域名处理类
 * 
 */
class DomainD {
    private static $_instance;
	public $excludeRoutes = array('www/category/categorydropdownlist'); //列外的路由

    private function __construct(){
		//负载均衡下，静态化时，如果是“从服务器”向“主服务器”的请求，则作以下处理
		//$_SERVER['HTTP_HOST'] = isset($_COOKIE['dld_static_http_host'])&&$_COOKIE['dld_static_http_host']?$_COOKIE['dld_static_http_host']:$_SERVER['HTTP_HOST'];
	}

	public static function getInstance(){
        if(!self::$_instance){
            self::$_instance = new DomainD();
		}

		return self::$_instance;
	}

    public function __clone()
    {
        trigger_error('Clone is not allow' ,E_USER_ERROR);
    }

	public function getDomain($url,$defaultDomain = 'default'){
		//域名处理
		$domain = '';
		if(strpos($url,'http') === 0){
            return $domain;
		}
		$domains = Yii::app()->params['domains'];
		$mapDomains = Yii::app()->params['mapDomains'];
		$params = array();
		//$urlParts = parse_url($url);
		parse_str(parse_url($url,PHP_URL_QUERY),$params);
		$r = isset($params['r'])?strtolower($params['r']):false;
		if(!in_array($r,$this->excludeRoutes)){
		    if($r){
			    $tmp = explode('/',$r);
			    while(!empty($tmp)){
                    $key = implode('/',$tmp);
				    if(isset($mapDomains[$key])){
                        $domain = isset($domains[$mapDomains[$key]])?$domains[$mapDomains[$key]]:'';
				        break;
				    }
				    array_pop($tmp);
			    }
		    }
            if(!$domain){
			    if($defaultDomain == 'default'){
                    $domain = isset($domains['localCity'])?$domains['localCity']:'';
			    }
			    else{
                    $domain = $defaultDomain;
			    }
		    }
		}
        
        return $domain;
	}

    /*
	*检查当前访问地址的域名是否与限定的域名一致，一致或者配置文件中没有配置的话则返回true,不一致则返回false,如果$forceReplace参数为true，则强制跳转为限制的域名
	*@param string $domainKey 在配置文件中域名domains数组中的key
	*/
	public function checkDomain($domainKey,$forceReplace = true){
        $domains = Yii::app()->params['domains'];
		$currentHost = $_SERVER['HTTP_HOST'];
		$rt = true;
		if(isset($domains[$domainKey])){
            if($domains[$domainKey] != 'http://'.$currentHost){
                if($forceReplace){
					$url = $domains[$domainKey].$_SERVER['REQUEST_URI'];
                    Yii::app()->request->redirect($url);
					Yii::app()->end();
				}
				else{
                    $rt = false;
				}
			}
		}

		return $rt;
	}

    /*
	*检查指定的cookie是否已经设置，如果没有设置，且$redirectUrl不为空，则跳到指定的url，如果为空则返回false.如果设置了，返回true
	*@param string $name cookie名
	*@param string $redirectUrl 没有设置指定cookie是要跳转的url
	*/
	public function checkCookie($name,$redirectUrl = ''){
		$cookie = Yii::app()->request->cookies[$name];
		$rt = false;
		if ($cookie instanceof CHttpCookie) {
			Yii::app()->controller->siteAreaCode=$cookie->value;
			$rt = true;
		}else{
			//如果指定cookie没有设置，且$redirectUrl不为空，则跳转到指定的url
			if($redirectUrl){
			    Yii::app()->request->redirect($redirectUrl);
				Yii::app()->end();
			}
		}

		return $rt;
	}
}
